package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 * 提供用户相关的 REST API
 * 
 * @author example
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 获取所有用户
     */
    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        log.info("请求获取所有用户");
        List<User> users = userService.getAllUsers();
        return ResponseEntity.ok(users);
    }

    /**
     * 根据 ID 获取用户
     */
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        log.info("请求获取用户，ID: {}", id);
        User user = userService.getUserById(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 异步获取用户
     */
    @GetMapping("/{id}/async")
    public ResponseEntity<User> getUserByIdAsync(@PathVariable Long id) {
        log.info("异步请求获取用户，ID: {}", id);
        User user = userService.getUserByIdAsync(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 创建用户
     */
    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        log.info("请求创建用户: {}", user.getName());
        User createdUser = userService.createUser(user);
        if (createdUser != null) {
            return ResponseEntity.ok(createdUser);
        } else {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        log.info("请求更新用户，ID: {}", id);
        User updatedUser = userService.updateUser(id, user);
        if (updatedUser != null) {
            return ResponseEntity.ok(updatedUser);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        log.info("请求删除用户，ID: {}", id);
        boolean deleted = userService.deleteUser(id);
        if (deleted) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 搜索用户
     */
    @GetMapping("/search")
    public ResponseEntity<List<User>> searchUsers(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String email) {
        log.info("请求搜索用户，name: {}, email: {}", name, email);
        List<User> users = userService.searchUsers(name, email);
        return ResponseEntity.ok(users);
    }

    /**
     * 使用 Map 参数搜索用户
     */
    @PostMapping("/search")
    public ResponseEntity<List<User>> searchUsersWithMap(@RequestBody Map<String, Object> params) {
        log.info("使用Map参数搜索用户: {}", params);
        List<User> users = userService.searchUsersWithMap(params);
        return ResponseEntity.ok(users);
    }

    /**
     * 带认证的获取用户
     */
    @GetMapping("/{id}/auth")
    public ResponseEntity<User> getUserWithAuth(
            @PathVariable Long id,
            @RequestHeader("Authorization") String authorization) {
        log.info("带认证请求获取用户，ID: {}", id);
        // 移除 "Bearer " 前缀
        String token = authorization.replace("Bearer ", "");
        User user = userService.getUserWithAuth(id, token);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 带重试机制的获取用户
     */
    @GetMapping("/{id}/retry")
    public ResponseEntity<User> getUserWithRetry(@PathVariable Long id) {
        log.info("带重试机制请求获取用户，ID: {}", id);
        User user = userService.getUserWithRetry(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 使用自定义 API（带签名）获取用户列表
     */
    @GetMapping("/with-sign")
    public ResponseEntity<List<User>> getUsersWithSign() {
        log.info("带签名请求获取用户列表");
        List<User> users = userService.getUsersWithSign();
        return ResponseEntity.ok(users);
    }

    /**
     * 使用自定义 API（带签名）根据 ID 获取用户
     */
    @GetMapping("/{id}/with-sign")
    public ResponseEntity<User> getUserWithSign(@PathVariable Long id) {
        log.info("带签名请求获取用户，ID: {}", id);
        User user = userService.getUserWithSign(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 演示搜索功能
     */
    @GetMapping("/demo/search")
    public ResponseEntity<String> demonstrateSearchFeatures() {
        log.info("演示搜索功能");
        userService.demonstrateSearchFeatures();
        return ResponseEntity.ok("搜索功能演示完成");
    }
} 